package tf_idf;

import javafx.util.Pair;
import util.StockSorter;
import util.StockSorterImpl;
import vo.StockInfo;

import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TF_IDFImpl implements TF_IDF {
	/**
	 * this func you need to calculate words frequency , and sort by frequency. you
	 * maybe need to use the sorter written by yourself in example 1
	 *
	 * @param words
	 *            the word after segment
	 * @return a sorted words
	 * @see StockSorter
	 */
	@Override
	public Pair<String, Double>[] getResult(List<String> words, StockInfo[] stockInfos) {
		// TODO: write your code here
		Set<String> wordSet = new HashSet<String>();
		// 将List中的分词结果存入Set中进行除重
		for (String temp : words) {
			wordSet.add(temp);
		}

		// 先计算除重后的所有分词结果的TF值, 并以Pair数组的形式返回
		Pair<String, Double>[] pairArray = calculateTF(words, wordSet);
		// 再计算除重后的所有分词结果的IDF值,通过修改传入的Pair数组元素值来保存修改结果
		calculateIDF(pairArray, stockInfos);
		// 至此得到正确的未排序的数组pairArray,开始降序排序排序
		StockSorterImpl sorter = new StockSorterImpl();
		return sorter.sort(pairArray);

	}

	/**
	 * TF--将计算结果存入Pair类型数组中返回
	 * 
	 * @param words
	 * @param wordSet
	 * @return
	 */
	private Pair<String, Double>[] calculateTF(List<String> words, Set<String> wordSet) {
		@SuppressWarnings("unchecked")
		Pair<String, Double>[] pairArray = (Pair<String, Double>[]) Array.newInstance(Pair.class, wordSet.size());
		int i = 0;
		for (String temp : wordSet) {
			int cnt = 0;// 用来统计temp在words中出现的次数
			for (int j = 0; j < words.size(); j++) {
				if (words.get(j).equals(temp)) {
					cnt++;
				}
			}
			// 在这之前已经拿到了temp的出现的次数
			Pair<String, Double> pair = new Pair<String, Double>(temp, (double) cnt / words.size());
			pairArray[i] = pair;
			i++;
		}
		return pairArray;

	}

	/**
	 * IDF--通过修改传入的Pair数组元素值来保存修改结果
	 * 
	 * @param pairArray
	 * @param stockInfos
	 */
	private void calculateIDF(Pair<String, Double>[] pairArray, StockInfo[] stockInfos) {
		for (int i = 0; i < pairArray.length; i++) {
			int cnt = 0; // 用于统计pairArray[i]中key(String)出现的次数
			for (StockInfo temp : stockInfos) {
				if (temp.getANSWER().indexOf(pairArray[i].getKey()) != -1) {
					cnt++;
				}
			}
			// 至此已统计完pairArray[i]中key(String)出现的次数
			// 开始将TF-IDF值重新写入数组pairArray中储存
			double IDF = Math.log((double) stockInfos.length / (cnt + 1));
			double TF_IDF = pairArray[i].getValue() * IDF;
			Pair<String, Double> pair = new Pair<String, Double>(pairArray[i].getKey(), TF_IDF);
			pairArray[i] = pair;
		}
	}
}
